//
//  ADOperation.swift
//  ADKit
//
//  Created by Adoma on 2024/01/23.
//

import RxSwift

open class ADOperation: Operation {
    
    public init(isAsynchronous: Bool = false) {
        _asynchronous = isAsynchronous
        super.init()
    }
    
    open override func start() {
        if isCancelled {
            finish()
            return
        }
        execute()
    }
    
    open func execute() {
        _executing = true
        ADLogger(adkit: Self.self)
            .debug(self.debugDescription,#function)
    }
    
    private enum ModifyState: String {
        case isExecuting = "isExecuting"
        case isFinished = "isFinished"
    }

    private var _executing: Bool = false {
        willSet{
            willChangeValue(forKey: ModifyState.isExecuting.rawValue)
        }
        didSet{
            didChangeValue(forKey: ModifyState.isExecuting.rawValue)
        }
    }
    
    private var _finished: Bool = false {
        willSet{
            willChangeValue(forKey: ModifyState.isFinished.rawValue)
        }
        didSet{
            didChangeValue(forKey: ModifyState.isFinished.rawValue)
        }
    }
    
    private let _asynchronous: Bool
    
    open override var isExecuting: Bool { _executing }
    open override var isFinished: Bool { _finished }
    open override var isAsynchronous: Bool { _asynchronous }
    
    open override func cancel() {
        super.cancel()
        if isExecuting {
            _executing = false
            _finished = true
        }
    }

    open func finish() {
        if isExecuting {
            _executing = false
        }
        _finished = true
    }
    
    deinit {
        ADLogger(adkit: Self.self)
            .debug(self.debugDescription,#function)
    }
}

